package com.merchant.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.merchant.entity.ResultData;
import com.merchant.entity.RuiShengUserInfo;
import com.merchant.service.RsMerchantInfoService;
import com.merchant.service.impl.MerchantServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @program: merchant-register
 * @description: 批量录入
 * @author: Vincent
 * @create: 2019-02-14 09:00
 **/
@Component("batchRegister")
public class BatchRegister {
    private static Logger log = LoggerFactory.getLogger("BatchRegister");

    @Autowired
    private MerchantServiceImpl merchantService;

    @Autowired
    private RsMerchantInfoService rsMerchantInfoService;

    @Autowired
    private MerchantNameHelperFace merchantNameHelper;

    @Autowired
    private ShenYangAccountAssistant shenYangAccountAssistant;

    @Autowired
    private RedisUtil redisUtil;


    // 进件过程中返回的重复的商户名称列表
    private List<String> repeatMerchantNameList;

    // 要进件的个数
    public int REGIST_COUNT = 0;


    /**
     * 执行批量进件
     *
     * @return ResultData
     */
    public ResultData execute() {

        // 从缓存中取重复的商户名称
        String redisKey = "SY_REPEAT_MERCHANT_NAME";
        Object repeatObj = redisUtil.lGet(redisKey, 0, redisUtil.lGetListSize(redisKey));
        if (repeatObj != null) {
            repeatMerchantNameList = (List<String>) repeatObj;
        } else {
            repeatMerchantNameList = Lists.newArrayList();
        }


        // 查询已经进件的商铺
        List<String> alreadyRegMchNameList = null;
        try {
            alreadyRegMchNameList = rsMerchantInfoService.getAllName();
        } catch (Exception e) {
            e.printStackTrace();
        }


        // 获取店铺信息(名称)
        String doorPicFolder = "E:\\滨农进件资料\\沈阳\\沈阳二类卡进件-20190309\\商户-沈阳-0309\\进件商户门头照-沈阳-20190309";
        String shopInfoPath = "E:\\滨农进件资料\\沈阳\\沈阳二类卡进件-20190309\\商户-沈阳-0309\\进件商户信息-沈阳-20190309.xlsx";
        List<Object> shopNameList = merchantNameHelper.getShopNameFromFile(shopInfoPath, doorPicFolder);

        // 获取二类卡信息
        List<RuiShengUserInfo> userList = shenYangAccountAssistant.getUserFromFile();
        List<String> notRegisterNameList = Lists.newArrayList(Splitter.on(",").split("王宁,马丽华,赵铁军,范莉娜"));
        userList = userList.stream().filter(userInfo -> (!notRegisterNameList.contains(userInfo.getPayname()))).collect(Collectors.toList());

        REGIST_COUNT = userList.size() * 16;
        int userCount = userList.size();
        log.info("execute() 要进件总数=" + REGIST_COUNT + ", 提供的总商户数=" + shopNameList.size());

        // 记录连续错误次数
        int continuousErrCount = 0;

        String a = "一芳,老王头饺子K0U,串记忆,铁板烧KcY,蒸美味7Ak,铁板烧XvE,煮动力时尚火锅,蛋糕先生,甜蜜约定烘焙坊,牛街炭火烤肉专门店,金豪音乐酒吧,麻辣地带,吉古焖面,汤姆之家汉堡披萨,尚品驴肉馆,北国渔村,青禾面馆,家和酒店,老大一站式烧烤,老渔坊,盛府火锅,崔记熏酱小酒馆,香轩源灶台鱼,佳园重庆烤鱼,鲜族大酒店,孟家饺子馆,金笸箩重庆小面,隆门圣宴,老兵之家营养火锅,我的亿万面包,252韩式烤肉,柯米烘焙坊,魅力岛烧烤特色烤羊,爱转角火锅串串,东港海鲜阁,小时候文化主题餐厅,盛宴烤肉,熬鱼馆铁锅炖鱼一绝,东北酸菜锅,东东火锅城,谭宝麻辣烤鱼,徒手海鲜,火锅记忆,大韩味道,范氏麻辣香锅,浩德天香烤肉,汤岗子北苑温泉酒店,串串香28元自助,让签签飞,碧海云天海鲜烧烤,炭牛平价烤牛肉,左岸邻汀,怡茶,小野戈厕所串串,小熙牛家章鱼水煎肉,阿良火锅,瑞客厨房休闲餐厅,小牧牛,湘都府风味土菜馆,柴火大队铁锅炖,食乐王婆大虾,老乡亲铁锅坊,九旗全羊烤吧,冠恒潮汕牛肉火锅,正红旗烧鸽子,熙姐姐的美食店,吉平川骄火锅,多乐美鲜花烘焙坊,麦希金烘焙屋,名都晓荷塘主题火锅,后街羊腿一绝,山河屯铁锅炖鱼,韩轩阁炭火烤肉,米米多水果捞,123量贩式烧烤,牛里韩式炭火烤肉,隆胜达粥店,王记麻辣烤鱼,喔寿司,吹牛啤海鲜烧烤,晓妹儿巷子烤肉,盱眙至尊龙虾,温州阿汤瘦肉丸,食路得老菜馆,聚德意北京烤鸭店,韩味时代紫菜包饭,贪吃正品龙虾,立新饺子馆,万福小木屋啤酒店,老屁孩8080年代,鑫乐春饼庄稼院,真味斋烤鸭坊,天天烤,家乡味凤城特色炸串,小海鲜串烧,神炭烧烤,弗尤斯,小熊嘎家酸菜煎肉,MA小美家,新北都烧烤店,慈必轩素食自助餐厅,PE主题休闲吧,老地方熏酱工厂,匠人渔场,神品串吧,邱记四川水煮鱼,于记坊香辣虾,太平洋丽晶酒店,久久巧手菜烀饼店,驴肉饺子馆,天月茶生活,韩云龙炭火烤肉,正秀烧烤,超媛鲜奶吧,香满楼饺子,那时光咖啡馆,隆佳烧烤,魅音乐串吧,福客来,鼎丰西部烤场,馅饼羊杂骨头馆,乡里乡亲民俗土菜,金种子农家院,品椒嗨辣私房小厨,碳老大京城涮羊肉,新罗食代,谷绩粥工馆,阿里郎串城,木火灶台馆,秦王令,喜朗朗水饺,MYCake蛋糕店,蒂唯施咖啡,滋道蛋糕,一点DIY烘培坊,焙多芬烘培坊,融豆烘焙,天龙烤肉冷面店,妮可蛋糕店,Henrys,甜蜜蜜烘焙坊,百吉事,牛角日式木炭烧烤肉,美时加蛋糕,乐乐烧烤,WI温莎堡蛋糕店,大签子,湘情铁板烧,十三太煲,三千里烤肉原始泥炉,大米范儿翻糖蛋糕艺,福满来火锅烤肉串吧,好时利烘焙蛋糕,成福蛋糕面包坊,苗医生专业祛痘祛斑,嫒手嫒脚美甲工作室,千千公主SPA会所,玛尔诗美甲美睫皮肤,SO神气能量氧身馆,泰式宫廷足疗AM馆,东宫SPA养生会馆,吕一道推拿,中曼泰式古法养生,一品足道,千荷汇养生足道会馆,御锦茗苑禅茶足道,圣族林御公馆,缔梵熙女子浴馆,江南水乡温泉,宝俪足道,鸿胜私人俱乐部,兴兴网苑,嘉沐汤泉,御康堂,曼特生活,格雷迪男士SP会馆,SP潮牌饮食搅局,三合足道,玉泉宫温泉养生会馆,懂串烧烤,大禹治水音乐现场酒,宋祥记海鲜烧烤,嘉香麻辣串串,周八啤音乐串吧,羊坊涮肉,A全球零食公馆,鑫盛铜火锅,香宝烤肉,锦州筋烧烤,巴鲜锅涮烤全鱼,甲乙丙吃烤肉吧,辣味仙麻辣香锅,伊维萨,炭火吧,如果有家下午茶,川仔烧烤碳铜火锅,渝味村,潮糖手作,鲜牛村碳火烤肉,重庆乾宗火锅,大驴小驴海鲜烤吧,成都遇见你,汇烤岁月,家和龟锅烤肉,小铜人火锅,武记无烟烧烤,刘鸡头烧烤,醉松记,屯门炭火烤肉,大韩烤肉,金刚山烤肉,火乐鸟春饼,九倒拐串串香,天香一品主题火锅,串门串串香火锅,臭啤匠精酿啤酒餐吧,美滋cake,小笨牛炭火烤肉,鲜族老式烤肉,百一大地锅,老北京肉饼,花间草堂咖啡,牛尾吧餐,华明口腔门诊,微笑口腔杨帆口腔诊,胡医生口腔,谢医生口腔,阳光口腔种植中心,天兴口腔正畸种植,畅途轮胎行,洗车王国RYl,盛子剪头烫染造型空,吉豆造型店,首爱造型,吉利来蛋糕,柠檬酷儿鲜茶坊,爆米花量贩式ayR,华清源养生洗浴,米高美KTV,麦霸Ba,江原松骨养生会馆,喜乐迪量贩式KTV,炭客29海鲜烧烤,铁板烧1F9,LON8Y,金悦烤肉,金韩雅,六婆串串香火ZpL,韩帝园民俗烤肉,云鼎丰火锅一站式体,爱锅者养生火aci,大龙盲人AMxeu";
        List<String> nameList = Lists.newArrayList(Splitter.on(",").split(a));


        // 遍历前N条
        int handledCount = 0;
        int index = 0;
        while (handledCount < REGIST_COUNT) {

            // 是否超时
            if (AddressHelper.outOfTimeRange()) {
                log.info("当前时间不在进件时间内[06:00-23:00]");
                break;
            }

            if (index >= shopNameList.size()) {
                log.info("已经轮询到结尾=" + index);
                break;
            }

            // 商户名称
            Map<String, String> obj = (Map<String, String>) shopNameList.get(index);
            String merchantName = obj.get("name");
            // 初始商户名称
            String originalName = merchantName;
            // 索引递增
            index = index + 1;


            // 格式化商户名称
            merchantName = merchantNameHelper.formatMerchantName(merchantName, originalName);

            // 11日添加的数据
            if (nameList.contains(merchantName)) {
                log.error("3月11日重复名称=" + merchantName);
                continue;
            }


            // 最终检查商铺名称是否超过10个字符
            if (merchantName.length() >= 10) {
                log.error("该商铺名称超过或等于10个字符=" + originalName);
                continue;
            }
            // 是否已经进件
            if (alreadyRegMchNameList.contains(merchantName)) {
                try {
                    FileUtils.removeDoneFile(getDoorPicFile(originalName, doorPicFolder), doorPicFolder);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                continue;
            }
            // 是否已经重复
            if (repeatMerchantNameList.contains(merchantName)) {
                // 去掉空格
                String randomName = merchantName.replaceAll("[^\u4e00-\u9fa5a-zA-Z0-9]", "");
                if (randomName.length() > 6) {
                    randomName = randomName.substring(0, 6);
                }
                merchantName = randomName + AddressHelper.getRandomStr(3);
            }


            // 生成客服号码
            String phone = PhoneNumHelper.genPhoneNum();
            // 生成邮箱
            String email = AddressHelper.getEmail(phone);


            // 获取门头照图片，检查是否存在
            File doorPicFile = getDoorPicFile(originalName, doorPicFolder);
            if (doorPicFile == null) {
                log.error("根据名称=" + originalName + "找不到对应的图片文件");
                continue;
            }


            // 获取省市区编码
            String provinceName = obj.get("province");
            String cityName = obj.get("city");
            String areaName = obj.get("area");
            String address = obj.get("address");
            String provinceCode = obj.get("provinceCode");
            String cityCode = obj.get("cityCode");
            String areaCode = obj.get("areaCode");
            if (StringUtils.isEmpty(provinceCode) || StringUtils.isEmpty(cityCode) || StringUtils.isEmpty(areaCode)) {
                log.error("没有获取到对应的省市区编号=" + address);
                continue;
            }


            // 上传门头照
            String doorPicUrl = FileUploadHandler.uploadFile(doorPicFile);
            if (doorPicUrl == null) continue;


            // 生成完整商户信息
            int userIndex = handledCount % userCount;
            RuiShengUserInfo userInfo = userList.get(userIndex);
            userInfo = RuiShengUserInfo.supplementParams(userInfo, merchantName, provinceCode, cityCode, areaCode, address, doorPicUrl,
                    provinceName, cityName, areaName, phone, email, originalName);


            boolean isSucc = false;
            // 进件
            try {
                // 调用进件接口
                ResultData addResult = merchantService.insert(userInfo);

                // 解析进件返回结果
                String addContent = (String) addResult.getData();
                JSONObject addJson = JSONObject.parseObject(addContent);
                int registerRet = addJson.getInteger("code");
                // 添加成功
                if (registerRet == 1) {
                    // 计数
                    handledCount += 1;
                    isSucc = true;

                    // 移除门头照图片
                    try {
                        FileUtils.removeDoneFile(getDoorPicFile(originalName, doorPicFolder), doorPicFolder);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    // 睡眠时间
                    if (handledCount < REGIST_COUNT) {
                        try {
                            Random random = new Random();
                            int sleepTime = random.nextInt(30) + 150;
                            log.info("休眠时间=" + sleepTime);
                            TimeUnit.SECONDS.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                } else {
                    if (addJson.getString("msg").contains("已有商户使用该商户名称")) {
                        repeatMerchantNameList.add(merchantName);
                        redisUtil.lRightPush(redisKey, merchantName);
                    }
                }
                log.info("批量商户进件结果[" + handledCount + "]=" + registerRet + ", " + addResult.getData());
                continuousErrCount = 0;

            } catch (Exception e) {
                e.printStackTrace();
                continuousErrCount += 1;
                log.error("商户进件异常=" + e.getMessage());
            }

            // 如果连续错误5次，则退出
            if (continuousErrCount >= 5) {
                log.error("executor() 连续出现异常次超过5次，退出进件");
                break;
            }


            // 睡眠时间
            if (handledCount < REGIST_COUNT && !isSucc) {
                try {
                    Random random = new Random();
                    int sleepTime = random.nextInt(10) + 5;
                    log.info("休眠时间=" + sleepTime);
                    TimeUnit.SECONDS.sleep(sleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        log.info("成功" + handledCount + "个。");
        return ResultData.getSuccessResult(handledCount);
    }

    /**
     * 根据名称获取门头照文件
     *
     * @param name 名称
     * @param path 门头照文件夹路径
     * @return File
     */
    public File getDoorPicFile(String name, String path) {
        File root = new File(path);
        File[] fileAr = root.listFiles();
        if (fileAr == null) {
            return null;
        }
        List<File> fileList = Lists.newArrayList(fileAr);
        for (File item : fileList) {
            if (item.getName().contains(name.trim())) {
                return item;
            }
        }
        return null;
    }


}
